﻿using DMS.Models;
using DMS.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DMS.Controllers
{
    public class LoginController : Controller
    {
        private readonly BUS.Bus _bus = new BUS.Bus();
        private readonly Security _security = new Security();
        public ActionResult Index(string returnUrl)
        {
            var model = new LoginModel();
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }       

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Index(LoginModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                var obj = _bus.Login(model);
                if (obj == null)
                {
                    ModelState.AddModelError("", "Bạn nhập sai thông tin đăng nhập.");
                }
                else
                {                    
                    Session.Timeout = 30;
                    _security.UserSignIn(obj, System.Web.HttpContext.Current);
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("index", "admin");
                    }
                    else
                    {
                        return Redirect(returnUrl);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Bạn nhập sai thông tin đăng nhập.");
            }
            return View(model);
        }

        [HttpPost]
        [AllowAnonymous]
        public JsonResult Logout()
        {
            _security.SignOutLocal(System.Web.HttpContext.Current);
            Session.Abandon();

            return Json(new { Status = 1 });
        }
    }
}
